package com.xique.door.command;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;

import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.UserDevice;
import com.xique.door.bean.domain.Visitor;
import com.xique.door.biz.service.impl.DeviceCommandServiceImpl;
import com.xique.door.constant.AccessCommandConstant;
import com.xique.door.device.command.AccessCommandHQService;
import com.xique.door.device.hq.bean.dto.HQResultDTO;
import com.xique.door.mapper.VisitorMapper;
import com.xique.door.service.IUserDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: caogq
 * @Date: 2021/7/8 09:55
 * @Description:
 */
@Service
public class VisitorCommandService {
    @Autowired
    private AccessCommandHQService accessCommandService;

    @Autowired
    private IUserDeviceService userDeviceService;

    @Autowired
    private VisitorMapper visitorMapper;
    //1、删除访客,批量
    public AjaxResult batchDelVisitor(String ids){
        List<String> idList = Convert.convert(List.class, ids);
        List<Visitor> visitors = visitorMapper.findVisitorListByIdList(idList);
        for (Visitor visitor : visitors) {
            //查出对应用户的设备
            UserDevice search = new UserDevice();
            search.setParkId(visitor.getParkId());
            search.setUserId(visitor.getUserId());
            List<UserDevice> userDevices = userDeviceService.selectUserDeviceList(search);
            //查出对应用户所绑定的设备
            List<String> devSns = userDevices.stream().map(UserDevice::getDevSn).distinct().collect(Collectors.toList());
            Map<String, String> customIdMap = new HashMap<>();
            customIdMap.put("customId", visitor.getCustomId());

            //下发
            Object obj = accessCommandService.delUserInfos(devSns, customIdMap, AccessCommandConstant.VERSION);

            DeviceCommandServiceImpl deviceCommandService = new DeviceCommandServiceImpl();
            AjaxResult result = deviceCommandService.getReturn(JSONObject.parseObject(obj.toString(), HQResultDTO.class));

            if (result.get("code").equals(AjaxResult.Type.ERROR)){
                return result;
            }

        }
        return AjaxResult.success();
    }
}
